package cc.rboot._core.helper;

import cn.hutool.core.util.TypeUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;

public class ClassHelper {
    public static List<Field> getAllFieldList(Class<?> clazz) {
        if (null == clazz) {
            return null;
        }
        List<Field> fieldList = new LinkedList<Field>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            /** 过滤静态属性**/
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            /** 过滤transient 关键字修饰的属性**/
            if (Modifier.isTransient(field.getModifiers())) {
                continue;
            }
            fieldList.add(field);
        }
        /** 处理父类字段**/
        Class<?> superClass = clazz.getSuperclass();
        if (superClass.equals(Object.class)) {
            return fieldList;
        }
        fieldList.addAll(getAllFieldList(superClass));
        return fieldList;
    }

    public static Class<?> getTypeArgument(Class<?> beanClass, Integer pos) {
        return (Class<?>) TypeUtil.getTypeArguments(beanClass)[pos];
    }

    public static boolean hasInterface(Class<?> targetClass, Class<?> interfaceClass) {
        for (Class<?> anInterface : targetClass.getInterfaces()) {
            if (anInterface == interfaceClass) {
                return true;
            }
            if (ClassHelper.hasInterface(anInterface, interfaceClass)) {
                return true;
            }
        }
        return false;
    }
}
